# -*- coding: utf-8 -*-
"""
字幕解析器 - 解析SRT/VTT字幕文件
参考项目实现
"""

import re
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
from datetime import timedelta


@dataclass
class SubtitleSegment:
    """字幕片段 - 存储字幕的时间戳和文本"""
    index: int
    start_time: float  # 秒
    end_time: float    # 秒
    text: str
    duration: float = 0.0  # 时长（秒）

    def __post_init__(self):
        """计算时长"""
        if self.duration == 0.0:
            self.duration = self.end_time - self.start_time


class SubtitleParser:
    """字幕解析器"""

    @staticmethod
    def parse_srt_time(time_str: str) -> float:
        """
        解析SRT时间戳为秒数

        Args:
            time_str: 时间戳字符串，格式如 "00:00:01,500"

        Returns:
            秒数
        """
        # 匹配格式: 00:00:01,500 或 00:00:01.500
        m = re.match(r"(\d\d):(\d\d):(\d\d)[\.,](\d\d\d)", time_str.strip())
        if not m:
            return 0.0

        hours, minutes, seconds, milliseconds = m.groups()
        total_seconds = (
            int(hours) * 3600
            + int(minutes) * 60
            + int(seconds)
            + int(milliseconds) / 1000.0
        )
        return total_seconds

    @staticmethod
    def format_srt_time(seconds: float) -> str:
        """
        将秒数格式化为SRT时间戳

        Args:
            seconds: 秒数

        Returns:
            时间戳字符串
        """
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        milliseconds = int((seconds - int(seconds)) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{milliseconds:03d}"

    @classmethod
    def load_srt(cls, file_path: Path) -> List[SubtitleSegment]:
        """
        加载SRT字幕文件

        Args:
            file_path: 字幕文件路径

        Returns:
            字幕片段列表
        """
        if not file_path.exists():
            return []

        subtitles = []

        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()

        # 分割字幕块
        blocks = [b.strip() for b in content.split("\n\n") if b.strip()]

        for block in blocks:
            lines = block.splitlines()
            if len(lines) < 3:
                continue

            # 提取索引（可选）
            index = 0
            if lines[0].strip().isdigit():
                index = int(lines[0].strip())
                time_line = lines[1].strip()
                text_lines = lines[2:]
            else:
                time_line = lines[0].strip()
                text_lines = lines[1:]

            # 解析时间线
            m = re.match(
                r"(\d\d:\d\d:\d\d[\.,]\d\d\d)\s*-->\s*(\d\d:\d\d:\d\d[\.,]\d\d\d)",
                time_line,
            )
            if not m:
                continue

            start_time = cls.parse_srt_time(m.group(1))
            end_time = cls.parse_srt_time(m.group(2))
            text = "\n".join(text_lines).strip()

            subtitle = SubtitleSegment(
                index=index or len(subtitles) + 1,
                start_time=start_time,
                end_time=end_time,
                text=text,
            )
            subtitles.append(subtitle)

        return subtitles

    @classmethod
    def validate_subtitles(cls, subtitles: List[SubtitleSegment]) -> Tuple[bool, List[str]]:
        """
        验证字幕列表

        Args:
            subtitles: 字幕片段列表

        Returns:
            (是否有效, 错误列表)
        """
        errors = []

        if not subtitles:
            errors.append("No subtitles found")
            return False, errors

        # 检查时间连续性
        for i in range(len(subtitles) - 1):
            current = subtitles[i]
            next_sub = subtitles[i + 1]

            # 检查时间是否重叠
            if current.end_time > next_sub.start_time:
                errors.append(
                    f"Subtitle {current.index} overlaps with {next_sub.index}: "
                    f"{current.end_time:.3f}s > {next_sub.start_time:.3f}s"
                )

            # 检查时间是否倒序
            if current.end_time >= next_sub.end_time:
                errors.append(
                    f"Subtitle {current.index} ends after {next_sub.index}: "
                    f"{current.end_time:.3f}s >= {next_sub.end_time:.3f}s"
                )

        # 检查持续时间
        for subtitle in subtitles:
            if subtitle.duration <= 0:
                errors.append(
                    f"Subtitle {subtitle.index} has non-positive duration: {subtitle.duration:.3f}s"
                )
            elif subtitle.duration < 0.5:
                errors.append(
                    f"Subtitle {subtitle.index} is very short: {subtitle.duration:.3f}s"
                )
            elif subtitle.duration > 10.0:
                errors.append(
                    f"Subtitle {subtitle.index} is very long: {subtitle.duration:.3f}s"
                )

        return len(errors) == 0, errors

    @classmethod
    def get_coverage_stats(cls, subtitles: List[SubtitleSegment], total_duration: float) -> dict:
        """
        获取字幕覆盖统计

        Args:
            subtitles: 字幕片段列表
            total_duration: 总时长

        Returns:
            统计信息字典
        """
        if not subtitles:
            return {
                "total_count": 0,
                "covered_duration": 0.0,
                "coverage_ratio": 0.0,
                "gaps": [],
            }

        covered_duration = 0.0
        gaps = []

        # 计算覆盖时长
        for i, subtitle in enumerate(subtitles):
            covered_duration += subtitle.duration

            # 检查间隙
            if i > 0:
                prev_end = subtitles[i - 1].end_time
                gap_start = prev_end
                gap_end = subtitle.start_time
                gap_duration = gap_end - gap_start

                if gap_duration > 0.1:  # 忽略小于100ms的间隙
                    gaps.append(
                        {
                            "start": gap_start,
                            "end": gap_end,
                            "duration": gap_duration,
                        }
                    )

        return {
            "total_count": len(subtitles),
            "covered_duration": covered_duration,
            "coverage_ratio": covered_duration / total_duration if total_duration > 0 else 0.0,
            "gaps": gaps,
        }

    @classmethod
    def analyze_sync_quality(cls, subtitles: List[SubtitleSegment]) -> dict:
        """
        分析同步质量

        Args:
            subtitles: 字幕片段列表

        Returns:
            质量分析结果
        """
        if not subtitles:
            return {"quality": "no_data", "issues": ["No subtitles found"]}

        issues = []
        warnings = []

        # 检查时间连续性
        for i in range(len(subtitles) - 1):
            current = subtitles[i]
            next_sub = subtitles[i + 1]
            gap = next_sub.start_time - current.end_time

            if gap < 0:
                issues.append(f"Subtitle {current.index} overlaps with {next_sub.index}")
            elif gap > 0.5:
                warnings.append(
                    f"Large gap between {current.index} and {next_sub.index}: {gap:.3f}s"
                )

        # 检查时长分布
        durations = [s.duration for s in subtitles]
        avg_duration = sum(durations) / len(durations)

        for i, subtitle in enumerate(subtitles):
            if subtitle.duration < 0.5:
                warnings.append(f"Subtitle {subtitle.index} is very short: {subtitle.duration:.3f}s")
            elif subtitle.duration > avg_duration * 2:
                warnings.append(f"Subtitle {subtitle.index} is very long: {subtitle.duration:.3f}s")

        # 质量评级
        if issues:
            quality = "poor"
        elif len(warnings) > len(subtitles) * 0.3:
            quality = "fair"
        else:
            quality = "good"

        return {
            "quality": quality,
            "issues": issues,
            "warnings": warnings,
            "subtitle_count": len(subtitles),
            "avg_duration": avg_duration,
        }
